﻿using AntMovement.Core.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AntMovement.PCI9016.Domain
{
    public class HardwareUpdateAxis : AntMovement.Core.IHardwareUpdate
    {
        private Axis _axis;

        public HardwareUpdateAxis(Axis axis)
        {
            _axis = axis;
        }

        public string Update()
        {
            int pPos = 0;
            int error = PCI9016.p9016_get_pos((int)_axis.AxisID, 0, ref pPos);
            if (error != 0)
            {
                return $"轴号[{_axis.AxisID}] p9016_get_pos 错误代码：{(PCI9016Error)error}";
            }
            _axis.Status.CurrentPostion = pPos;
            if (_axis.AxisID < 4)
            {
                error = PCI9016.p9016_get_pos((int)_axis.AxisID, 1, ref pPos);
                if (error != 0)
                {
                    return $"轴号[{_axis.AxisID}] p9016_get_pos 错误代码：{(PCI9016Error)error}";
                }
                _axis.Status.EqPostion = pPos;
            }
            uint pstatus = 0;
            error = PCI9016.p9016_get_motion_status((int)_axis.AxisID, ref pstatus);
            if (error != 0)
            {
                return $"轴号[{_axis.AxisID}] p9016_get_motion_status 错误代码：{(PCI9016Error)error}";
            }
            _axis.Status.SportStatus = pstatus == 1;
            double pvel = 0;
            error = PCI9016.p9016_get_current_speed((int)_axis.AxisID, ref pvel);
            if (error != 0)
            {
                return $"轴号[{_axis.AxisID}] p9016_get_current_speed 错误代码：{(PCI9016Error)error}";
            }
            _axis.Status.CurrentSpeed = pvel;
            error = PCI9016.p9016_get_io_status((int)_axis.AxisID, ref pstatus);
            _axis.Status.El_Left = (pstatus & 0x01) == 1;
            _axis.Status.El_Right = ((pstatus >> 1) & 0x01) == 1;
            _axis.Status.ORG = ((pstatus >> 2) & 0x01) == 1;
            _axis.Status.EZ = ((pstatus >> 3) & 0x01) == 1;
            _axis.Status.EMG = ((pstatus >> 4) & 0x01) == 1;
            return "ok";
        }
    }
}
